import numpy as np
import pandas as pd

np.random.seed(1)

df = pd.DataFrame({
    "key1": ["a", "a", "b", "b", "a"],
    "key2": ["one", "two", "one", "two", "one"],
    "data1": np.random.randn(5),
    "data2": np.random.randn(5)
})
print(df)
'''
  key1 key2     data1     data2
0    a  one  2.019750  0.827016
1    a  two  0.801902 -0.280143
2    b  one  1.017911  1.059884
3    b  two  0.078757 -1.080313
4    a  one  1.369262  1.294918
'''
'''
以某一列为参照物对另一列进行分组统计
'''
# 按key1分组, 计算data1列的平均值
key1 = df["data1"].groupby(df["key1"]).mean()
'''
key1
a    1.396971
b    0.548334
Name: data1, dtype: float64
'''
# 语法糖为
key1 = df.groupby(["key1"])["data1"].mean()
'''
key1
a    1.396971
b    0.548334
Name: data1, dtype: float64
'''
'''以某几列为参照物对另一列进行分组统计'''
key12 = df["data1"].groupby([df["key1"], df["key2"]]).count()
'''
key1  key2
a     one     2
      two     1
b     one     1
      two     1
Name: data1, dtype: int64
'''
'''以任意数组为分组键对另一列进行分组统计'''
arr = np.array([1993, 1994, 1993, 1996, 1996])
print(df)
'''
  key1 key2     data1     data2
0    a  one  2.019750  0.827016
1    a  two  0.801902 -0.280143
2    b  one  1.017911  1.059884
3    b  two  0.078757 -1.080313
4    a  one  1.369262  1.294918
'''
df["data1"].groupby(arr).mean()
'''
1993    1.518830
1994    0.801902
1996    0.724010
Name: data1, dtype: float64
'''
# 分组迭代
for name, group in df.groupby("key1"):
    print(name, '*' * 3, '\n', group)
'''
a *** 
   key1 key2     data1     data2
0    a  one  2.019750  0.827016
1    a  two  0.801902 -0.280143
4    a  one  1.369262  1.294918
b *** 
   key1 key2     data1     data2
2    b  one  1.017911  1.059884
3    b  two  0.078757 -1.080313
'''
# 聚合操作
df = pd.DataFrame({'A': [1, 1, 2, 2],
                   'B': [1, 2, 3, 4],
                   'C': np.random.randn(4)})
print(df)
'''
   A  B         C
0  1  1  0.129248
1  1  2 -0.144462
2  2  3 -1.227830
3  2  4 -0.417642
'''
res = df.groupby('A').agg('min')
print(res)
'''
   B        C
A             
1  1 -0.144462
2  3 -1.227830
'''
res = df.groupby('A').agg(['min', 'max'])
print(res)
'''
    B             C          
  min max       min       max
A                            
1   1   2 -0.144462  0.129248
2   3   4 -1.227830 -0.417642
'''
# 具体到某一列
res = df.groupby('A').B.agg(['min', 'max'])
print(res)
'''
   min	max
A		
1	1	2
2	3	4
'''
# 每一列分别聚合
res = df.groupby('A').agg({'B': ['min', 'max'], 'C': 'sum'})
print(res)
'''
    B             C
  min max       sum
A                  
1   1   2  -0.015214
2   3   4  -1.645473
'''
# 指定不为索引
res = df.groupby(["A"], as_index=False)["B"].agg({"C": "count"})
'''
   A  B         C
0  1  1  0.129248
1  1  2 -0.144462
2  2  3 -1.227830
3  2  4 -0.417642
'''
print(res)
'''
   A  C
0  1  2
1  2  2
'''
